#include "semaphore.h"

union semun {
	int              val;    /* Value for SETVAL */
	struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
	unsigned short  *array;  /* Array for GETALL, SETALL */
	struct seminfo  *__buf;  /* Buffer for IPC_INFO (Linux-specific) */
};
	
int semaphore_create(const char *path, int project_id)
{
	key_t key;
	
	//根据磁盘路径和项目id生成key值
	key = ftok(path, project_id);
	if(key == -1)
		return -1;
	//创建或打开一个信号量集合
	return semget(key, 1, IPC_CREAT|0666);
}

int semaphore_post(int semaphore_id)
{
	struct sembuf ops;
	
	//操作信号量
	ops.sem_num = 0;	//要操作的信号量编号
	ops.sem_op = 1;		//sem_op>0,释放sem_op次，sem_op<0，获取|sem_op|次
#ifndef USE_FOR_LOCK
	ops.sem_flg = 0;	//操作标准，有SEM_UNDO、IPC_NOWAIT
#else
	ops.sem_flg = SEM_UNDO;
#endif
	return semop(semaphore_id, &ops, 1);
}

int semaphore_wait(int semaphore_id)
{
	struct sembuf ops;
	
	ops.sem_num = 0;
	ops.sem_op = -1;
#ifndef USE_FOR_LOCK
	ops.sem_flg = 0;
#else
	ops.sem_flg = SEM_UNDO;
#endif
	return semop(semaphore_id, &ops, 1);
}

int semaphore_set_value(int semaphore_id, int value)
{
	union semun set_value;
	
	//设置信号量的值
	set_value.val = value;
	return semctl(semaphore_id, 0, SETVAL, set_value);
}

int semaphore_get_value(int semaphore_id)
{
	//获取信号量的值
	return semctl(semaphore_id, 0, GETVAL);
}

int semaphore_delete(int semaphore_id)
{
	//删除信号量集合
	return semctl(semaphore_id, 0, IPC_RMID);
}